﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraLayout;
using DevExpress.XtraLayout.Utils;
using DevExpress.XtraEditors.Controls;
using System.Drawing;
using DevExpress.XtraGrid;
using DevExpress.Data;
using System.Collections;
using Framework.Domain;

namespace CIIS.Common
{
    public partial class Manage : BaseUserControl
    {
        IList dataSource = null;

        Type optFormType = null;
        Type entityType = null;

        LayoutControlItem[] lcisQueryParam = null;
        LayoutControlItem[] lcisButton = null;

        public string defaultExportName { get; set; }

        public Manage()
        {
            InitializeComponent();

            lcisQueryParam = new LayoutControlItem[] { lciQuery1, lciQuery2, lciQuery3, lciQuery4, lciQuery5, lciQuery6, lciQuery7, lciQuery8 };
            foreach (LayoutControlItem p in lcisQueryParam)
            {
                p.Visibility = LayoutVisibility.Never;
            }
            lcisButton = new LayoutControlItem[] { lciBtn1, lciBtn2, lciBtn3, lciBtn4 };
            foreach (LayoutControlItem b in lcisButton)
            {
                b.Visibility = LayoutVisibility.Never;
            }

            buttonClean.Click += new EventHandler(buttonClean_Click);
            buttonExport.Click += new EventHandler(buttonExport_Click);

            //gridControlData.DataSource = new[] { new {test = "1"}, new{test="2"}};
            //repositoryItemHyperLinkEdit1.Click += new EventHandler(repositoryItemHyperLinkEdit1_Click);

            //InitGridViewOperateColumns(new string[] { "审核" }, new EventHandler[] { new EventHandler(repositoryItemHyperLinkEdit1_Click) });
        }

        void repositoryItemHyperLinkEdit1_Click(object sender, EventArgs e)
        {
            XtraMessageBox.Show("您点击了链接列");
        }

        #region 按钮事件，包括列的链接事件
        void buttonExport_Click(object sender, System.EventArgs e)
        {
            try
            {
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.FileName = defaultExportName;
                dlg.DefaultExt = "xls";
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    gridControlData.ExportToXls(dlg.FileName, new DevExpress.XtraPrinting.XlsExportOptions()
                     {
                         Suppress65536RowsWarning = true,
                         ShowGridLines = true
                     });
                }
            }
            catch
            {
                XtraMessageBox.Show("导出文件失败，请关闭同名已打开文件。");
            }
        }

        void buttonClean_Click(object sender, System.EventArgs e)
        {
            for (int i = 0; i < lcisQueryParam.Length; i++)
            {
                if (lcisQueryParam[i].Visibility == LayoutVisibility.Always)
                {
                    if (lcisQueryParam[i].Control is SearchLookUpEdit)
                    {
                        (lcisQueryParam[i].Control as SearchLookUpEdit).EditValue = null;
                    }
                    else
                    {
                        lcisQueryParam[i].Control.Text = string.Empty;
                    }
                }
            }
        }

        void linkDetail_Click(object sender, System.EventArgs e)
        {
            BaseForm bf = optFormType.Assembly.CreateInstance(optFormType.FullName) as BaseForm;
            bf.OptType = EOperateType.Detail;
            bf.ShowDialog();
        }

        void linkDelete_Click(object sender, System.EventArgs e)
        {
            List<Entity> entityList = GetCheckedEntitys();
            if (entityList.Count == 0)
            {
                entityList.Add(GetFocusedRowDataEntity());
            }
            if (XtraMessageBox.Show(string.Format("是否要删除选中的{0}条记录？", entityList.Count), "删除确认", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                foreach (Entity v in entityList)
                {
                    v.State.MarkDeleted();
                    dao.Dao.SaveOrUpdate(v);
                }

                dao.ReloadDataList(entityType.Name);
                BindGridData(entityType);
            }
        }
        void linkVerify_Click(object sender, System.EventArgs e)
        {
            BaseForm bf = optFormType.Assembly.CreateInstance(optFormType.FullName) as BaseForm;
            bf.OptType = EOperateType.Verify;
            if (bf.ShowDialog() == DialogResult.OK)
            {
                dao.ReloadDataList(entityType.Name);
                BindGridData(entityType);
            }
        }
        void linkChange_Click(object sender, System.EventArgs e)
        {
            BaseForm bf = optFormType.Assembly.CreateInstance(optFormType.FullName) as BaseForm;
            bf.OptType = EOperateType.Change;
            if (bf.ShowDialog() == DialogResult.OK)
            {
                dao.ReloadDataList(entityType.Name);
                BindGridData(entityType);
            }
        }
        void linkModify_Click(object sender, System.EventArgs e)
        {
            BaseForm bf = optFormType.Assembly.CreateInstance(optFormType.FullName) as BaseForm;
            bf.OptType = EOperateType.Modify;
            Entity entity = GetFocusedRowDataEntity();
            if (entity != null)
            {
                bf.BindData(entity);
                if (bf.ShowDialog() == DialogResult.OK)
                {
                    dao.ReloadDataList(entityType.Name);
                    BindGridData(entityType);
                }
            }
        }

        private Entity GetFocusedRowDataEntity()
        {
            Entity rowData = null;
            int rowHandle = gridViewData.FocusedRowHandle;
            if (rowHandle >= 0)
            {
                rowData = gridViewData.GetRow(rowHandle) as Entity;
            }
            return rowData;
        }

        private List<Entity> GetCheckedEntitys()
        {
            List<Entity> entityList = new List<Entity>();
            for (int i = 0; i < gridViewData.DataRowCount; i++)
            {
                Entity entity = gridViewData.GetRow(i) as Entity;
                if (entity != null && entity.IsSelected)
                {
                    entityList.Add(entity);
                }
            }
            return entityList;
        }

        void buttonAdd_Click(object sender, System.EventArgs e)
        {
            BaseForm bf = optFormType.Assembly.CreateInstance(optFormType.FullName) as BaseForm;
            bf.OptType = EOperateType.Add;
            bf.BindData(null);
            if (bf.ShowDialog() == DialogResult.OK)
            {
                dao.ReloadDataList(entityType.Name);
                BindGridData(entityType);
            }
        }

        #endregion

        #region 初始化

        public void RegisterOptFormType(Type dlgType)
        {
            optFormType = dlgType;
        }

        public void BindGridData(Type dataType)
        {
            entityType = dataType;
            dataSource = dao.GetListFromCache(dataType.Name);
            gridControlData.DataSource = dataSource;
        }

        /// <summary>
        /// 初始化按钮
        /// </summary>
        /// <param name="buttonName"></param>
        /// <param name="evts"></param>
        public void InitButtonsWithEvent(string[] buttonName, EventHandler[] evts)
        {
            if (buttonName == null || evts == null || buttonName.Length != evts.Length)
            {
                return;
            }
            for (int i = 0; i < lcisButton.Length && i < buttonName.Length; i++)
            {
                lcisButton[i].Visibility = LayoutVisibility.Always;
                if (lcisButton[i].Control != null)
                {
                    Button btn = lcisButton[i].Control as Button;
                    if (btn != null)
                    {
                        btn.Text = buttonName[i];
                        btn.Click += evts[i];
                    }
                }
            }
        }

        public void InitButtonsWithFlag(string[] optCaptionName, EOperateType[] optFlags)
        {
            EventHandler[] evts = GetEventsByFlag(optFlags);

            InitButtonsWithEvent(optCaptionName, evts);
        }

        /// <summary>
        /// 初始化查询条件 
        /// </summary>
        /// <param name="visibleFlags"></param>
        /// <param name="titles"></param>
        /// <param name="bindParams"></param>
        public void InitParamControl(bool[] visibleFlags, string[] titles, DropdownControlParam[] bindParams)
        {
            for (int i = 0; i < visibleFlags.Length && i < lcisQueryParam.Length; i++)
            {
                if (visibleFlags[i])
                {
                    lcisQueryParam[i].Visibility = LayoutVisibility.Always;
                    lcisQueryParam[i].Size = new Size(130, 24);
                    lcisQueryParam[i].Text = titles[i];
                    if (bindParams[i] != null && lcisQueryParam[i].Control is SearchLookUpEdit)
                    {
                        SearchLookUpEdit slue = lcisQueryParam[i].Control as SearchLookUpEdit;
                        DevControlUtils.Instance.InitSearchLookUpEdit(slue, bindParams[i]);
                    }
                }
            }
        }

        /// <summary>
        /// 初始化普通列必须在初始化操作列之前
        /// </summary>
        /// <param name="columnNames"></param>
        /// <param name="fieldNames"></param>
        /// <param name="bindDatas"></param>
        public void InitGridViewDataColumns(string[] columnNames, string[] fieldNames, DropdownControlParam[] bindDatas)
        {
            if (columnNames == null || fieldNames == null || columnNames.Length != fieldNames.Length)
            {
                return;
            }
            gridViewData.Columns.Clear();
            for (int i = 0; i < columnNames.Length; i++)
            {
                GridColumn col = new GridColumn() { Caption = columnNames[i], FieldName = fieldNames[i] };
                col.VisibleIndex = gridViewData.Columns.Count;
                if (bindDatas != null && bindDatas.Length > i && bindDatas[i] != null)
                {
                    RepositoryItemLookUpEdit rilue = new RepositoryItemLookUpEdit();
                    DevControlUtils.Instance.InitRepositoryItemLookUpEdit(rilue, bindDatas[i]);
                    col.ColumnEdit = rilue;
                }
                gridViewData.Columns.Add(col);
            }
        }

        /// <summary>
        /// 加载操作列
        /// </summary>
        /// <param name="optCaptionName"></param>
        /// <param name="ents"></param>
        public void InitGridViewOptColumnWithEvent(string[] optCaptionName, EventHandler[] ents)
        {
            if (optCaptionName == null || ents == null || optCaptionName.Length != ents.Length)
            {
                return;
            }
            for (int i = 0; i < optCaptionName.Length; i++)
            {
                GridColumn col = new GridColumn();
                col.VisibleIndex = gridViewData.Columns.Count;
                RepositoryItemHyperLinkEdit link = new RepositoryItemHyperLinkEdit();
                EditorButton be = new EditorButton();
                be.Caption = optCaptionName[i];
                be.Appearance.Font = new Font(new FontFamily("Tahoma"), 10, FontStyle.Underline);
                be.Appearance.Options.UseFont = true;
                be.Kind = ButtonPredefines.Glyph;
                link.TextEditStyle = TextEditStyles.HideTextEditor;
                link.Buttons.Add(be);
                link.Click += ents[i];
                col.ColumnEdit = link;
                gridViewData.Columns.Add(col);
            }
        }

        public void InitGridViewOptColumnWithFlag(string[] optCaptionName, EOperateType[] optFlags)
        {
            EventHandler[] ents = GetEventsByFlag(optFlags);

            InitGridViewOptColumnWithEvent(optCaptionName, ents);
        }

        private EventHandler[] GetEventsByFlag(EOperateType[] optFlags)
        {
            EventHandler[] ents = new EventHandler[optFlags.Length];
            for (int i = 0; i < optFlags.Length; i++)
            {
                switch (optFlags[i])
                {
                    case EOperateType.Add:
                        ents[i] = new EventHandler(buttonAdd_Click);
                        break;
                    case EOperateType.Change:
                        ents[i] = new EventHandler(linkChange_Click);
                        break;
                    case EOperateType.Delete:
                        ents[i] = new EventHandler(linkDelete_Click);
                        break;
                    case EOperateType.Detail:
                        ents[i] = new EventHandler(linkDetail_Click);
                        break;
                    case EOperateType.Modify:
                        ents[i] = new EventHandler(linkModify_Click);
                        break;
                    case EOperateType.Verify:
                        ents[i] = new EventHandler(linkVerify_Click);
                        break;
                }
            }
            return ents;
        }

        public void SetDefaultSortColumn(string fieldName, bool isAscending)
        {
            GridColumn col = gridViewData.Columns[fieldName];
            if (col != null)
            {
                gridViewData.ClearSorting();
                col.SortIndex = 0;
                col.SortMode = ColumnSortMode.DisplayText;
                col.SortOrder = isAscending ? ColumnSortOrder.Ascending : ColumnSortOrder.Descending;
            }
        }
        //private GridView CreateSlueView(string valueMember, string displayMember)
        //{
        //    var searchLookUpEditView = new GridView()
        //        {
        //            FocusRectStyle = DrawFocusRectStyle.RowFocus,
        //            Name = "searchLookUpEditView"
        //        };
        //    searchLookUpEditView.OptionsSelection.EnableAppearanceFocusedCell = false;
        //    searchLookUpEditView.OptionsView.ShowGroupPanel = false;
        //    searchLookUpEditView.Columns.AddRange(new GridColumn[] {
        //        CreateGridColumn(displayMember,"请选择条件")});
        //    return searchLookUpEditView;
        //}

        //private static GridColumn CreateGridColumn(string member, string type)
        //{
        //    var gridColumn = new GridColumn()
        //    {
        //        Caption = type,
        //        FieldName = member,
        //        Name = "gridColumn" + member,
        //        Visible = true,
        //        VisibleIndex = 0
        //    };
        //    return gridColumn;
        //}
        #endregion

        public List<string> GetParams()
        {
            List<string> paramList = new List<string>();
            for (int i = 0; i < lcisQueryParam.Length; i++)
            {
                if (lcisQueryParam[i].Visibility == LayoutVisibility.Always)
                {
                    string param = lcisQueryParam[i].Control.Text ?? string.Empty;
                    paramList.Add(param);

                    //if (lcis[i].Control is TextEdit)
                    //{
                    //    param = (lcis[i].Control as TextEdit).Text;
                    //}
                    //else if (lcis[i].Control is SearchLookUpEdit)
                    //{
                    //    param = (lcis[i].Control as SearchLookUpEdit).Text;
                    //}
                }
            }
            return paramList;
        }
    }

}
